//! 网络协议处理模块
//! 
//! 该模块负责处理各种网络协议的编解码和消息路由

use std::sync::Arc;
use std::collections::HashMap;
use tokio::sync::RwLock;
use tracing::{info, error, warn};

use nacos_core::traits::{NetworkService, NetworkRequest, NetworkResponse};
use nacos_core::{ClusterNode, NacosError};
use nacos_core::Result;

pub mod handler;
pub mod codec;
pub mod router;

pub use handler::*;
pub use codec::*;
pub use router::*;

/// 协议处理器工厂
pub struct ProtocolHandlerFactory;

impl ProtocolHandlerFactory {
    /// 根据协议类型创建对应的处理器
    pub fn create_handler(protocol: &str) -> Box<dyn ProtocolHandler> {
        match protocol {
            "nacos_grpc" => Box::new(NacosGrpcHandler::new()),
            "http" => Box::new(HttpHandler::new()),
            "tcp" => Box::new(TcpHandler::new()),
            _ => {
                warn!("未知协议类型: {}", protocol);
                Box::new(UnsupportedHandler::new())
            }
        }
    }
}

/// 协议处理器trait
#[async_trait::async_trait]
pub trait ProtocolHandler: Send + Sync {
    /// 处理请求
    async fn handle_request(
        &self,
        request: NetworkRequest,
        source_node: Option<ClusterNode>,
    ) -> Result<NetworkResponse>;

    /// 处理响应
    async fn handle_response(
        &self,
        response: NetworkResponse,
        source_node: Option<ClusterNode>,
    ) -> Result<()>;

    /// 获取支持的协议类型
    fn supported_protocols(&self) -> Vec<String>;

    /// 协议名称
    fn name(&self) -> String;
}

/// 协议路由器
pub struct ProtocolRouter {
    handlers: Arc<RwLock<HashMap<String, Box<dyn ProtocolHandler>>>>,
    network_service: Arc<dyn NetworkService>,
}

impl ProtocolRouter {
    pub fn new(network_service: Arc<dyn NetworkService>) -> Self {
        Self {
            handlers: Arc::new(RwLock::new(HashMap::new())),
            network_service,
        }
    }

    /// 注册协议处理器
    pub async fn register_handler(
        &self,
        protocol: String,
        handler: Box<dyn ProtocolHandler>,
    ) {
        let mut handlers = self.handlers.write().await;
        handlers.insert(protocol.clone(), handler);
        info!("注册协议处理器: {}", protocol);
    }

    /// 路由请求到对应的协议处理器
    pub async fn route_request(
        &self,
        protocol: &str,
        request: NetworkRequest,
        source_node: Option<ClusterNode>,
    ) -> Result<NetworkResponse> {
        let handlers = self.handlers.read().await;
        
        match handlers.get(protocol) {
            Some(handler) => {
                handler.handle_request(request, source_node).await
            }
            None => {
                error!("未找到协议处理器: {}", protocol);
                Err(NacosError::Protocol(format!("不支持的协议: {}", protocol)))
            }
        }
    }

    /// 路由响应到对应的协议处理器
    pub async fn route_response(
        &self,
        protocol: &str,
        response: NetworkResponse,
        source_node: Option<ClusterNode>,
    ) -> Result<()> {
        let handlers = self.handlers.read().await;
        
        match handlers.get(protocol) {
            Some(handler) => {
                handler.handle_response(response, source_node).await
            }
            None => {
                error!("未找到协议处理器: {}", protocol);
                Err(NacosError::Protocol(format!("不支持的协议: {}", protocol)))
            }
        }
    }
}

/// 协议配置
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct ProtocolConfig {
    /// 支持的协议列表
    pub supported_protocols: Vec<String>,
    /// 默认协议
    pub default_protocol: String,
    /// 协议特定配置
    pub protocol_configs: HashMap<String, serde_json::Value>,
}

impl Default for ProtocolConfig {
    fn default() -> Self {
        let mut protocol_configs = HashMap::new();
        
        // gRPC配置
        protocol_configs.insert("nacos_grpc".to_string(), serde_json::json!({
            "port": 9090,
            "max_concurrent_streams": 100,
            "compression": true
        }));
        
        // HTTP配置
        protocol_configs.insert("http".to_string(), serde_json::json!({
            "port": 8848,
            "max_connections": 1000,
            "timeout": 30000
        }));
        
        Self {
            supported_protocols: vec!["nacos_grpc".to_string(), "http".to_string()],
            default_protocol: "nacos_grpc".to_string(),
            protocol_configs,
        }
    }
}